// pages/task/taskSubmit.js
const httpUtils = require('../../utils/httpUtils')
const ui = require('../../utils/ui')
const systemInfo = wx.getWindowInfo();
const bottomInset = Math.abs(systemInfo.safeArea.bottom - systemInfo.windowHeight);  

Page({

  /**
   * 页面的初始数据
   */
  data: {
    task_requirement: '',
    requirement_images: [],
    upload_files: [],
    comment: '',
    order_no: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      scrollViewBottomInset: bottomInset+64,
      bottomInset: bottomInset
    });
    this.requestTaskDetail(options.taskNo);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  //点击图片预览
  previewImage(event){
    var currentUrl = event.currentTarget.dataset.src //获取当前点击图片链接
    var urls = event.currentTarget.dataset.urls //获取当前图片列表
    wx.previewImage({
      current:currentUrl,//当前点击的预览图片地址
      urls: urls,//需要预览的图片列表，这是必须设置的属性
    })
  },
  //图片选择后
  afterRead(event) {
    const { file } = event.detail;    
    var that = this
    const upload_files = that.data.upload_files
    //获得这次上传的图片数量，上传时避免重复上传之前传过的文件
    const thisNum = file.length 
    const beforeNum = upload_files.length 
    const totalNum = thisNum + beforeNum
    //还没上传时将选择的图片的上传状态设置为加载    
    for (let j = 0; j < thisNum; j++) {
      file[j].status='uploading'
      upload_files.push(file[j])
    }
    that.setData({ upload_files })
    // console.log('fileList',that.data.fileList)
    // console.log('file',file)
    //上传服务器
    for (let i = beforeNum; i < totalNum; i++) {
          that.uploadImg(i,that.data.upload_files[i].url )
    }
  },
  uploadImg(fileListIndex,fileURL) {
    var that = this
    //上传文件
    const filePath = fileURL // 小程序临时文件路径
    // console.log("filePath",filePath)
    wx.uploadFile({
      url: 'https://shangjinxia.ltd/api/image/file',
      filePath: filePath,
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data",
      },
      formData: { 
        fileType:'image',
        reName:'true',
        thumbnail:'true'
      },
      success(res) {
      var tem = JSON.parse(res.data)
      // 上传完成需要更新 fileList
      that.setData({
        [`upload_files[${fileListIndex}].url`]: tem.uploadFileUrl,
        [`upload_files[${fileListIndex}].status`]: 'done'
      })
      ui.showToast('上传成功')
      },
      fail: function (res) {
        console.log("file upload fail")
      },
    })
  },
  deleteImage(event) {
    const {
      upload_files = []
    } = this.data;
    upload_files.splice(event.detail.index);
    this.setData({
      upload_files
    });
  },
  //提交任务结果
  actionTask() {
    var that = this;
    var uploadList = [];
    var uploadSuccess = true;
    this.data.upload_files.forEach(element => {
      if (element.status == 'done') {
        uploadList.push(element.url);
      } else {
        uploadSuccess = false;
      }
    });
    if (!uploadSuccess) {
      ui.showToast("有图片未上传成功");
      return;
    }
    console.log(uploadList);
    console.log('备注'+this.data.comment);
    if (uploadList.length == 0 && this.data.comment.length == 0) {
      wx.showModal({
        title: '提示',
        content: '当前提交内容为空，是否继续提交',
        complete: (res) => {
          if (res.confirm) {
            that.requestSubmitTask();
          }
        }
      });
      return;
    }
    this.requestSubmitTask();
  },
  requestSubmitTask() {
    var uploadList = [];
    this.data.upload_files.forEach(element => {
      uploadList.push(element.url)
    });
    let obj = {
      method: 'POST',
      url: '/task-order/' + wx.getStorageSync('USERDATA').platformId + '/' + this.data.order_no + '/submit',
      showLoading: true,
      data: {
        images: uploadList,
        comment: this.data.comment
      }
    }
    httpUtils.request(obj).then(res => {
      wx.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000,
        mask: true,
        success: function() {
          setTimeout(function() {
            wx.navigateBack({
              delta: 0,
            });
          }, 1500)
        }
      });
    }).catch(err => {
      console.log('ERROR')
    });
  },
  //请求任务详情
  requestTaskDetail(taskNo) {
    let obj = {
      method: 'GET',
      url: '/task/' + taskNo,
      showLoading: true,
      data: {
      }
    }
    httpUtils.request(obj).then(res => {
      this.setData({
        task_requirement: res.data.taskRequirement,
        requirement_images: res.data.taskRequirementImages,
        order_no: res.data.orderNo
      });
    }).catch(err => {
      console.log(err)
    });
  },
})